package com.zhongxi.guoyuan.view.personalCenter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedGood;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClearWeedSearchActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, ClearWeedExchangeAdapter.OnItemClickListener {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.iv_clearweed_search)
    ImageView ivClearweedSearch;
    @Bind(R.id.et_clearweed_search)
    EditText etClearweedSearch;
    @Bind(R.id.tv_clearsearch_recently)
    TextView tvClearsearchRecently;
    @Bind(R.id.tv_clearsearch_newest)
    TextView tvClearsearchNewest;
    @Bind(R.id.tv_clearsearch_sales)
    TextView tvClearsearchSales;
    @Bind(R.id.rv_clearsearch)
    RecyclerView rvClearsearch;
    @Bind(R.id.swiprf_clearsearch)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.search_no_find)
    TextView searchNoFind;


    private ClearWeedExchangeAdapter adapter;
    private List<ClearWeedGood> list = new ArrayList<>();

    private String type;
    private int orderby = 1;
    private String longitude;
    private String latitude;
    private String trim;
    private JSONObject storeInfo;
    private LinearLayoutManager layoutManager;
    private int visibleItemPosition;
    private boolean isLoading=false;
    private boolean isSearch;
    private ClearWeedResult clearWeedResult;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_clear_weed_search);
        ButterKnife.bind(this);
        initTitle();
        tvTitle.setText("兑换搜索");
    }

    @Override
    protected void initData() {
        super.initData();
        longitude = MyApplication.getInstance().getLongitude();
        latitude = MyApplication.getInstance().getLatitude();
        layoutManager = new LinearLayoutManager(this);
        rvClearsearch.setLayoutManager(layoutManager);
        adapter = new ClearWeedExchangeAdapter(this);
        rvClearsearch.setAdapter(adapter);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.red),getResources().getColor(R.color.title_blue));
        getAllData();

    }

    public void getAllData() {
        type = "data";
        String str = "&page=" + pageNum + "&orderBy=" + orderby + "&cateid=0" + "&lng=" + longitude + "&lat=" + latitude;
        getServer(Url.CLEARWEED_GOODLIST, null, str, false, null, "get");
    }

    public void getSearchData() {
        type = "data";
        Map<String, String> map = new HashMap<>();
        map.put("content", trim);
        String string = "&page=" + pageNum;

        getServer(Url.CLEARWEED_SEARCH, map, string, false, null, "post");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("data")) {
            clearWeedResult = gson.fromJson(response, ClearWeedResult.class);
            MyApplication.getInstance().setSpValue(clearWeedResult.getSafeobj());
            if (pageNum == 1) {
                list.clear();
            }
            if (clearWeedResult.getGoodsInfo() != null && clearWeedResult.getGoodsInfo().size() > 0) {
                list.addAll(clearWeedResult.getGoodsInfo());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    storeInfo = jsonObject.optJSONObject("store");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.setList(list, storeInfo);
                if (isSearch){
                    searchNoFind.setVisibility(View.GONE);
                }
            } else {
                if (pageNum > 2) {
                    adapter.setFooter_state(2);
                } else {
                    adapter.setFooter_state(0);
                }
                if (isSearch&&pageNum<2){
                    searchNoFind.setVisibility(View.VISIBLE);
                }
                pageNum--;
                if (pageNum < 1) {
                    pageNum = 1;
                }
                isLoading=false;
                adapter.notifyDataSetChanged();

            }

        }

        if (swipeRefreshLayout.isRefreshing()){
            swipeRefreshLayout.setRefreshing(false);
        }

    }

    @OnClick({R.id.ivBack, R.id.iv_clearweed_search, R.id.et_clearweed_search, R.id.tv_clearsearch_recently, R.id.tv_clearsearch_newest, R.id.tv_clearsearch_sales})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                onBackPressed();
                break;
            case R.id.iv_clearweed_search:
                trim = etClearweedSearch.getText().toString().trim();

                if (!trim.equals("") && trim.length() > 0){
                    getSearchData();
                    isSearch =true;
                }
                else {
                   getAllData();
                }
                CommonTool.hideSoft(etClearweedSearch,this);

                break;
            case R.id.et_clearweed_search:
                break;
            case R.id.tv_clearsearch_recently:
                setColor(tvClearsearchRecently, tvClearsearchNewest, tvClearsearchSales);
                orderby = 1;
                getData();
                break;
            case R.id.tv_clearsearch_newest:
                setColor( tvClearsearchNewest, tvClearsearchRecently,tvClearsearchSales);
                orderby = 2;
                getData();
                break;
            case R.id.tv_clearsearch_sales:
                setColor(tvClearsearchSales,tvClearsearchRecently, tvClearsearchNewest);

                orderby = 3;
                getData();
                break;
        }
    }

    private void getData() {
        trim = etClearweedSearch.getText().toString().trim();
        if (!trim.equals("") && trim.length() > 0)
            getSearchData();
        else
            getAllData();
    }

    public void setColor(TextView view1, TextView view2, TextView view3) {
        view1.setTextColor(getResources().getColor(R.color.title_red));
        view2.setTextColor(getResources().getColor(R.color.gohere));
        view3.setTextColor(getResources().getColor(R.color.gohere));
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        adapter.setItemClickListener(this);
        rvClearsearch.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState==RecyclerView.SCROLL_STATE_IDLE &&(visibleItemPosition+2)==adapter.getItemCount()&&!isLoading
                        &&!swipeRefreshLayout.isRefreshing()){
                    if (clearWeedResult.getGoodsInfo()!=null&&clearWeedResult.getGoodsInfo().size()>0){
                        trim=etClearweedSearch.getText().toString().trim();
                        pageNum++;
                        if (!trim.equals("")&&trim.length()>0)
                            getSearchData();
                        else
                            getAllData();

                        isLoading=true;
                        adapter.setFooter_state(1);
                    }else {
                        adapter.setFooter_state(2);
                    }

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemPosition = layoutManager.findLastVisibleItemPosition();
            }
        });
        swipeRefreshLayout.setOnRefreshListener(this);

    }

    @Override
    public void onRefresh() {
        pageNum=1;
        trim=etClearweedSearch.getText().toString().trim();
        getData();
    }

    @Override
    public void onClick(View view, int position) {
        ClearWeedGood clearWeedGood = list.get(position);
        Intent intent=new Intent(ClearWeedSearchActivity.this,ClearWeedDetailActivity.class);
        intent.putExtra("id",clearWeedGood.getId());
        startActivity(intent);
    }

    //判断手势滑动方向
    float x1,x2,y1,y2;
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_DOWN){
            //手指按下的时候
             x1 = event.getX();
             y1= event.getY();
        }
        if (event.getAction()==MotionEvent.ACTION_UP){
            x2=event.getX();
            y2=event.getY();

        }
        return super.onTouchEvent(event);

    }
}
